<template>
  <div>
    <el-steps :active="state.active" v-if="type != 1" align-center>
      <el-step title="项目基本信息" />
      <el-step title="项目阶段" />
      <el-step title="完成" />
    </el-steps>

    <el-form
      v-if="state.active == 1"
      :model="formInline"
      ref="formInlineRef"
      :rules="projectRules"
      class="demo-form-inline"
      label-width="180px"
    >
      <el-row>
<!--        <el-col :span="8">
          <el-form-item label="关联项目集" prop="projectSetId">
            <el-select
              v-model="formInline.projectSetId"
              clearable
              :disabled="type == 1"
              placeholder="关联项目集"
            >
              <el-option
                v-for="item in state.projectSetsList"
                :key="item.projectSetId"
                :label="item.projectSetName"
                :value="item.projectSetId"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              :disabled="type == 1"
              v-model="formInline.projectName"
              placeholder=""
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号">
            <el-input disabled v-model="formInline.projectId" placeholder="">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目分类" prop="projectTypeId">
            <el-select
              v-model="formInline.projectTypeId"
              clearable
              :disabled="type == 1"
              placeholder=""
              @change="streerTypeChange"
            >
              <el-option
                v-for="item in state.typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务单元" prop="businessUnit">
            <el-select
              v-model="formInline.businessUnit"
              clearable
              :disabled="type == 1"
              placeholder="业务单元"
              @change="streerTypeChange"
            >
<!--              <el-option
                v-for="item in businessUnitArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />-->
              <el-option v-for="(item,index) in businessUnitList" :key="index" :label="item.businessUnitName" :value="item.businessUnitId+''"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划实施时间范围" prop="time">
            <el-date-picker
              v-model="formInline.time"
              @change="handelChangeTime"
              :disabled="type == 1"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目位置" prop="streetCode">
            <el-select
              v-model="formInline.streetCode"
              clearable
              :disabled="type == 1"
              placeholder="项目位置"
              @change="streerChange"
            >
              <el-option
                v-for="item in state.streetList"
                :value="item.value"
                :key="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目详细地址" prop="address">
            <el-input
              :disabled="type == 1"
              v-model="formInline.address"
              placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拟计划总投额" prop="projectAmount">
            <el-input
              :disabled="type == 1"
              v-model.number="formInline.projectAmount"
              placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="projectType == 3">
          <el-form-item label="项目类型" prop="projectCategory">
            <el-select
              v-model="formInline.projectCategory"
              clearable
              :disabled="type == 1"
              placeholder="项目类型"
              @change="streerTypeChange"
            >
              <el-option value="1" label="公司自建"></el-option>
              <el-option value="2" label="政府投资"></el-option>
              <el-option value="3" label="代建项目"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目立项部门">
            <el-select
              v-model="formInline.responsibleDepartmentId"
              clearable
              disabled
              placeholder="项目立项部门"
              @change="departmentIdChange(formInline.responsibleDepartmentId)"
            >
              <el-option
                v-for="item in state.allDepartmentList"
                :key="item.departmentId"
                :label="item.departmentName"
                :value="item.departmentId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目负责人" prop="responsibleUserId">
            <el-select
              v-model="formInline.responsibleUserId"
              clearable
              :disabled="type == 1"
              placeholder="项目负责人"
              @change="streerTypeChange"
            >
              <el-option
                v-for="item in state.departmentPersonList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编码" prop="projectCode">
            <el-input
              :disabled="type == 1"
              v-model.number="formInline.projectCode"
              placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属业态" prop="typeOfBusiness">
            <el-select
              v-model="formInline.typeOfBusiness"
              clearable
              :disabled="type == 1"
              placeholder="所属业态"
              @change="streerTypeChange"
            >
              <el-option
                v-for="item in state.typeofBusinessList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
<!--          <el-col :span="8">
              <el-form-item label="政府项目" prop="isGovernment">
                  <el-radio-group v-model="formInline.isGovernment" class="ml-4">
                      <el-radio :label="0" size="large">否</el-radio>
                      <el-radio :label="1" size="large">是</el-radio>
                  </el-radio-group>
              </el-form-item>
          </el-col>-->
        <el-col :span="24">
          <el-form-item label="项目摘要">
            <el-input
              v-model="formInline.projectSummary"
              :disabled="type == 1"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="getURLhandler(route.path).type == 1">
          <el-form-item label="项目创建时间" prop="">
              <!--              :disabled="type == 1"-->
            <el-input
              :disabled="true"
              v-model.number="formInline.createTime"
              placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="项目创建人"
            prop=""
            v-if="getURLhandler(route.path).type == 1"
          >
<!--              :disabled="type == 1"-->
            <el-input
              :disabled="true"
              v-model.number="formInline.createUserName"
              placeholder=""
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--项目阶段-->
    <projectStageTree
      :projectTypeId="formInline.projectTypeId || getURLhandler(route.path).projectTypeId"
      :departmentList="state.allDepartmentList"
      ref="projectStagetree"
      :projectId="getURLhandler(route.path).projectId || state.projectId"
      v-if="state.active == 2"
    ></projectStageTree>


    <div class="buttons" v-if="state.active !== 3">
      <el-button v-if="state.active !==2" @click="goback">取消</el-button>
      <el-button
        v-if="type != 1"
        type="primary"
        @click="submitHandler()"
      >
        下一步
      </el-button>
      <el-button
        type="primary"
        v-if="type == 1 && formInline?.examineStatus == '0'"
        @click="type = 2"
      >
        编辑
      </el-button>
    </div>
    <div v-if="state.active == 3">
      <p style="height: 40px">
        <svg-icon
          icon-class="sucesss-icon"
          style="width: 100%; height: 100%"
        ></svg-icon>
      </p>
      <p
        style="
            font-size: 16px;
            text-align: center;
        "
      >
        {{
          `恭喜您，完成项目集的${
            getURLhandler(route.path).type ? '编辑' : '添加'
          }!`
        }}
      </p>
      <p
        style="
            font-size: 16px;
            text-align: center;
        "
      >
        <el-button @click="goback">返回列表页</el-button>
      </p>
    </div>
    <mapDialog ref="mapdialog" @getMapAddrInfo="getMapAddrInfo"></mapDialog>
  </div>
</template>
<script setup>
import { getURLhandler } from '@/views/constructionProjectManage/static/utools.js'
import '@/views/constructionProjectManage/static/button.scss'
import MapDialog from '@/views/constructionProjectManage/projectmanagement/components/mapDialog.vue'
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { assetsApi } from '@/api/assets'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from "vuex"
import { businessUnitArr } from '@/common/dict/dictCollect.js'
import ProjectStageTree from '@/views/constructionProjectManage/preliminaryProject/components/projectStageTree.vue'

import {
    projectApi,
    projectListApi,
    department,
    publicProject,
    projectConfigApi,
    projectPhase, darkLine
} from '@/api/project'
import { fundManagementApi } from '@/api/businessFinance'
import PublicDialog from '@/components/PublicDialog.vue'
import {
    ElTag,
    ElForm,
    ElSelect,
    ElFormItem,
    ElStep,
    ElButton,
    ElTree,
    ElSteps,
    ElDatePicker,
    ElMessage,
    ElRow,
    ElCol, ElOption,
    ElRadioGroup,
    ElRadio
} from 'element-plus'
const projectStagetree = ref(null)
const dialogForm = reactive({
  projectStageId: '',
  projectCode: '',
  projectId: '',
  responsibleDepartmentId: '',
  stageName: '',
  parentProjectStageId: '',
  stageOrder: '',
  level: ''
})
const state = reactive({
  streetList: [],
  //养老、教育、医疗、农贸、综合体、绿道、文体、子公司、其他
  typeofBusinessList: [
    {
      label: '养老',
      value: '1'
    },
    {
      label: '教育',
      value: '2'
    },
    {
      label: '医疗',
      value: '3'
    },
    {
      label: '农贸',
      value: '4'
    },
    {
      label: '综合体',
      value: '5'
    },
    {
      label: '绿道',
      value: '6'
    },
    {
      label: '文体',
      value: '7'
    },
    {
      label: '子公司',
      value: '8'
    },
    {
      label: '其他',
      value: '9'
    }
  ],
  projectId: '',
  projectSetsList: [],
  typeList: [],
  projectSetIdList: [],
  projectCategoryList: [
    {
      label: '公司自建',
      value: '1'
    },
    {
      label: '政府投资',
      value: '2'
    },
    {
      label: '代建项目',
      value: '3'
    }
  ],
  allDepartmentList: [],
  departmentPersonList: [],
  userByDepartmentList: [],
  projectTypeList: [],
  streerTypeOptionsArr: [],
  dataSource: [], //树行数据
  projectOptionsArr: [], //所有项目
  active: 1,
  success: false, //编辑或添加是否成功
  type: 0 //0新增 1编辑
})

let centerDialogVisible = ref(false)
let formInlineRef = ref(null)

const formInline = reactive({
  time: [],
  streetName: '',
  projectAmount:'',
  yearAmount:'',
  isGovernment:0
})
//路由跳转
let router = useRouter()
let route = useRoute()
const projectType = getURLhandler(route.path).projectType

// 1 编辑  0 新增 2修改
let type = ref(getURLhandler(route.path).type)
console.log('--分类-', projectType)
//判断是否编辑
let isUpdate = computed(() => {
  if (getURLhandler(route.path).type == 1) {
    return true
  } else {
    return false
  }
})
const projectRules = reactive({
  projectSetId: [
    { required: true, message: '关联项目集不能为空', trigger: 'change' }
  ],
  projectName: [
    { required: true, message: '项目名称不能为空', trigger: 'blur' }
  ],
  projectCode: [
    { required: true, message: '项目编码不能为空', trigger: 'blur' }
  ],
  projectTypeId: [
    { required: true, message: '项目分类不能为空', trigger: 'change' }
  ],
  businessUnit: [
    { required: true, message: '业务单元不能为空', trigger: 'change' }
  ],
  streetCode: [
    { required: true, message: '项目位置不能为空', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '项目详细地址不能为空', trigger: 'blur' }
  ],
  projectAmount: [
    { required: true, message: '拟计划总投额不能为空', trigger: 'blur' },
    { type: 'number', message: '金额只能为数字',}
  ],
  typeOfBusiness: [
    { required: true, message: '所属业态不能为空', trigger: 'change' }
  ],
  time: [
    { required: true, message: '计划实施时间范围不能为空', trigger: 'blur' }
  ],
  // responsibleDepartmentId: [
  // 	{ required: true, message: "项目立项部门不能为空", trigger: "change" },
  // ],
  responsibleUserId: [
    { required: true, message: '项目负责人不能为空', trigger: 'change' }
  ]
})
const mapdialog = ref(null)
const mapclick = () => {
  if (mapdialog?.value) {
    mapdialog.value.openMap()
  }
}

const getMapAddrInfo = (data) => {
  console.log(data)
  formInline.address = data.address
}

// 获取所有项目集
const getProjectSets = () => {
  fundManagementApi.getProjectSets().then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.projectSetsList = data
    }
  })
}
// 获取所有部门
const getAllDepartments = () => {
  department.getAllDepartments().then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.allDepartmentList = data
    }
  })
}
// 获取项目 负责人
let store = useStore()
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
  // console.log(store.state.user.departmentId,'---------');
  let departmentId = store.state.user.departmentId;
  department.getUserByDepartmentId(departmentId).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.departmentPersonList = data
    }
  })
}
// 获取项目 执行人员
// const getUserByDepartmentId = (responsibleDepartmentId) => {
// 	department.getUserByDepartmentId(responsibleDepartmentId).then((res) => {
// 		const { code, data, msg } = res;
// 		if (code == 200) {
// 			state.userByDepartmentList = data;
// 		}
// 	});
// };
// 获取项目类型
const getProjectTypeVo = () => {
  publicProject.getProjectTypeVo().then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.projectTypeList = data
    }
  })
}

//获取所有项目信息
const projectListApiHandler = () => {
  //新增查询
  //编辑查询
  let obj = {
    projectSetId: ''
  }
  if (isUpdate) {
    obj = {
      projectSetId: getURLhandler(route.path).edit || ''
    }
  }

  projectListApi.getAllList(obj.projectSetId || '').then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      state.projectOptionsArr = data
    }
  })
}

//街道变化
const streerTypeChange = (type) => {}
const departmentIdChange = (id) => {
  formInline.responsibleUserId = ''
}
//位置编号
const streerChange = (e) => {
  state.streetList.forEach((item) => {
    if (item.value == e) {
      formInline.streetName = item.label
    }
  })
}

// 监听 项目负责部门 调用 项目负责人
watch(
  () => formInline.responsibleDepartmentId,
  (value) => {
    if (value) {
      getLeaderByDepartmentId(value)
    }
  }
)

// 获取项目集
const getpublicProject = () => {
  projectConfigApi.getProjectSets().then((res) => {
    if (res.code == 200) {
      state.projectSetIdList = res.data.map((item) => {
        return {
          label: item.projectSetName,
          value: item.projectSetId
        }
      })
    }
  })
}
const getTypeList = (e) => {
  const type = '10' + e
  projectConfigApi.getTypeList(type).then((res) => {
    if (res.code == 200) {
      state.typeList = res.data.map((item) => {
        return {
          label: item.typeName,
          value: item.projectTypeId
        }
      })
    }
  })
}

const handelChangeTime = (e) => {
  console.log(e)
  if (e && e.length > 0) {
    formInline.predictStartTime = e[0]
    formInline.predictEndTime = e[1]
  }
}
//提交
const submitHandler = (formEl) => {
  if(!formEl) {
      if(getURLhandler(route.path).type == 0 && state.active==1){
          darkLine.createDarkProject({...formInline,isDark:1}).then((res) => {
              const { code, data, msg } = res
              if (code === '200') {
                  state.success = true
                  state.active = 2
                  ElMessage.success('新增成功')
                  state.projectId = data
              }
          })
      }

     if(state.active==2){
         if (projectStagetree.value.state.dataSource?.length === 0) {
             ElMessage.warning('请添加项目阶段')
             return
         }

         // 第二步
         projectStagetree.value.createStage(()=>{
             state.active = 3
             ElMessage.success("操作成功");
         });
     }
  }
}

//返回列表页
const goback = () => {
  router.push({
    path: '/constructionProjectManage/expectedplan/index'
  })
}
//通过ID获取详情
const getByidHandler = async (id) => {
  await projectListApi.getprojectByid(id).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      // initAreaOptions(2, data.regionCode)
      setTimeout(() => {
        Object.assign(formInline, data)
          formInline.businessUnit = formInline.businessUnit + '';
      }, 0)
      formInline.time = [data.predictStartTime, data.predictEndTime]
      // console.log("formInline.time ", formInline.time);
    }
  })
}
const initAreaOptions = (type = '2', cd = '') => {
  // type：1-获取区域 ；2-获取街道
  // cd：获取区域时不传
  assetsApi.getLocations(type, cd).then((res) => {
    const { code, data, msg } = res
    if (code == 200) {
      res.data.forEach((item) => {
        item.label = item.name
        item.value = item.code
      })
      state.streetList = res.data
    }
  })
}

/**
 * 获取业务单元
 */
const businessUnitList = ref([]);
const getFundBudgetBusinessUnitAll = () => {
    fundManagementApi.getFundBudgetBusinessUnitAll().then(res=>{
        if(res.code === '200'){
            businessUnitList.value = res.data;
        }
    });
}

defineExpose({
  centerDialogVisible,
  state
})
onMounted(() => {
  initAreaOptions()
  formInline.type = getURLhandler(route.path)?.projectType
  projectListApiHandler()
  getAllDepartments()
  getProjectSets()
  getpublicProject()
  getTypeList(getURLhandler(route.path)?.projectType)
  getProjectTypeVo()
  getFundBudgetBusinessUnitAll()
    if(getURLhandler(route.path).status!==undefined){
        state.active = getURLhandler(route.path).status;
    }
  if (getURLhandler(route.path).type != '0') {
    //编辑
    getByidHandler(getURLhandler(route.path)?.projectId || '')
  } else {
    formInline.responsibleDepartmentId = JSON.parse(
      window.localStorage.getItem('SST-DepartmentId')
    )
  }
})
</script>
<style lang="scss" scoped>
.demo-form-inline{
  margin-top: 32px;
  margin-bottom: 20px;
  border: 1px solid #E3E7F1 ;
  padding: 15px;
  border-radius: 10px;
}
.el-select {
  width: 50%;
}
.select_project {
  width: 100%;
}
.buttons {
  text-align: center;
}
.twoline {
  display: flex;
  .el-form-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .el-select {
      width: 100%;
    }
  }

  justify-content: space-between;
}
.oneline {
  .el-form-item {
    width: 100%;
  }
}
</style>

<style lang="scss" scoped>
.el-step__title.is-process,is-text{
  font-weight: normal !important;
  color: #a8abb2 !important;
}
.is-process{
  border-color: #a8abb2 !important;
}
.el-step__head.is-process{
  font-weight: normal !important;
  color: #a8abb2 !important;
}
.public-dialog-content {
  :deep(.el-form-item__content) {
    width: 100%;
  }
  .el-form {
    width: 400px;
  }
  .el-input,
  .el-select {
    width: 100%;
  }
}
.el-dialog__body .el-form .el-form-item {
  width: 100% !important;
}

.el-select {
  width: 100% !important;
}
</style>
